﻿@model App.Web.ViewModels.ProductViewModel
@using App.Web.Utility;
@using App.Core.Extensions;

@{
    String pageTitle = "Edit Product & Manage Product Images";
    if (Model != null && Model.ID == 0)
    {
        pageTitle = "Add New Product";
    }
    ViewBag.Title = Html.GetPageTitle(pageTitle);
    String categoryButtonText = Model.CategoryID > 0 ? "Change Category" : "Select Category";
    //String _SaveButtonCaption = Model.ID == 0 ? "Save" : "Save";
    List<App.Web.ViewModels.CategoryViewModel> _Categories = ApplicationCache.Categories;
    bool _IsSaved = TempData[AppConstants.ViewDataKeys.SAVED] == null ? false : TempData[AppConstants.ViewDataKeys.SAVED].ToString().ToBoolean();
    bool _IsAdded = TempData[AppConstants.ViewDataKeys.ADDED] == null ? false : TempData[AppConstants.ViewDataKeys.ADDED].ToString().ToBoolean();
    bool _HasValidationError = ViewData[AppConstants.ViewDataKeys.HAS_VALIDATION_ERROR] != null ? true : false ;    
}

<div class="page-heading">
    <h1>@pageTitle</h1>
    <div>
        Enter necessary information and then Upload Images (If Any) for this product.        
    </div>
</div>
@Html.Partial("_DatePicker") 
@if (Model != null)
{
    <script language="javascript" type="text/javascript">        
        var _CategoryDialog = null; 
        var _PictureDialog = null;  
        var _ImageDialog = null; 
        $(document).ready(function () {
           _CategoryDialog = $('#divCategoryDialog').dialog({
		        autoOpen: false,
		        title: 'Select Category',
                modal: true,                
		        width: $('#divCategoryDialog').width(),
                buttons:{
                    'Select':function(){ SelectCategory(); },
                    'Cancel': function(){ $(this).dialog('close'); }
                }
		    });
            _ImageDialog = $('#divImageDialog').dialog({
		        autoOpen: false,
		        title: 'Manage Product Images',
                modal: true,                
		        width: $('#divImageDialog').width(),
                height: $('#divImageDialog').height()
		    });            
            $('#dialog').dialog({
                autoOpen: false, width: 400,
                buttons: {
                    "Ok": function () { $(this).dialog("close"); }
                }
            });
            $('#btnCategorySelection').click(function(){
                $(_CategoryDialog).dialog('open');//alert($(this).val());
            });

            if (parseInt($('#CategoryID').val()) > 0)
                GetDynamicProperties(@Model.ID, $('#CategoryID').val());            
        });        
        function GetDynamicProperties(productID, categoryID) {
            var url = '@Url.Action("GetDynamicUI", "Product", new { area = AppConstants.Area.PRIVATE })';
            var data = 'productID=' + productID + '&categoryID=' + categoryID;
            var lglValues = $('#hdnSelectedValues').val();
            if(lglValues != undefined && lglValues != null && lglValues.length > 0)
                data += '&lglValues=' + lglValues;
            Ajax(url, data, function(result){
                $('#divDynamicProperty').html(result);
                var form = $('form');
                $(form).removeData('validator');
                $.validator.unobtrusive.parse(form);
            });
        } 
        function GetCategoryBreadCrumb(categoryID){
            var url = '@Url.Action("GetCategoryBreadCrumb", "Product", new { area = AppConstants.Area.PUBLIC })';
            var data = 'categoryID=' + categoryID;
            Ajax(url, data, function(result){ $('#spanSelectedCategory').html(result); HideLoadingAnimation(); }); 
        }
        function SelectCategory() {            
            var categoryID = $('#divCategoryDialog input[type=radio]:checked').val();
            if(categoryID == undefined || categoryID == null || categoryID == 0)            
                alert("Please Select a Category."); //$('#dialog').html('Please Select a Category.').dialog('open');            
            else
            {
                $(_CategoryDialog).dialog('close');
                ShowLoadingAnimation(false);
                GetDynamicProperties(@Model.ID, categoryID);
                GetCategoryBreadCrumb(categoryID);                
                $('#CategoryID').val(categoryID);                
            }
        }
        function ShowImageDialog(productID){
            $(_ImageDialog).dialog('open');
            var iFrame = $(_ImageDialog).find('iframe');
            if($(iFrame).attr('src').length == 0){
                ShowLoadingAnimation(false);
                $(iFrame).attr('src', '@Url.Action("List", "ProductImage", new { ID = Model.ID })');
            }            
        }
        function UpdateImageList(thumbnail, largePicture)
        {
            $('#divProductImages').show();
            var html = '';
            //var imgElements = $('#divProductImages img');            
            html += BuildLightboxImageElement(thumbnail, largePicture);
            $('#divProductImages div.set').append(html);
            $('#divManageImageLink').hide();
            //FIXME: Not Working
            $('#divProductImages a').lightBox({fixedNavigation:true});        
        }
        function DeleteFromImageList(thumbnail){
            var elementToRemove = null;
            $('#divProductImages').find('img').each(function(){
                if($(this).attr('src') == thumbnail){
                     elementToRemove = $(this).parent().parent();
                } 
            });
            if(elementToRemove != null)
                $(elementToRemove).remove();

            var imgElements = $('#divProductImages img');      
            if(imgElements.length == 0){
                $('#divProductImages').hide();
                $('#divManageImageLink').show();
            }            
        }
        function BuildLightboxImageElement(thumbnail, largePicture){
            return '<div class="single"><a href="' + largePicture + '" rel="lightbox[ProductAlbum]" title="Click on the Right/Left side of the image to move Forward/Reverse."><img src="' + thumbnail + '" alt="Image 3 0f 3 thumb" /></a></div>';
        }
        function AdjustiFrameHeight(height) {
            $('#iframeImageList').height(height);
        }
        function ChildHideLoading(){            
            HideLoadingAnimation();
        }
    </script>
}
<div class="GroupBox">
@using (Html.BeginForm())
{    
    @Html.ValidationSummary(true)
    Html.EnableClientValidation(true);
    if (Model == null)
    {
        @: @Html.ErrorMessageBox("Sorry! Requested Product was not found for edit.")
    }
    else
    {
        if (_IsAdded)
        {
            @: @Html.InfoMessageBox("Product added successfully. Now add few images for this product to look better in the site. To manage images click on the Manage Product Iamges.")
        }
        else if (_IsSaved)
        {
            @: @Html.InfoMessageBox("Product Saved Successfully.")
        }
        <div class="editor-label">
		    @Html.LabelFor(model => model.CategoryID)
	    </div>            
	    <div class="editor-field">			
            <span id="spanSelectedCategory">
            @if (Model.CategoryID > 0)
            {
                @Html.GetCategoryBreadCrumb(Model.CategoryID, true)
            }
            </span>
            <input id="btnCategorySelection" type="button" value="@categoryButtonText"/>
            @Html.HiddenFor(model => model.CategoryID)
		    @Html.ValidationMessageFor(model => model.CategoryID)
            @Html.HiddenFor(model => model.CompanyID)
	    </div>
        <div class="editor-label">
			@Html.LabelFor(model => model.Name)
		</div>
		<div class="editor-field">
			@Html.EditorFor(model => model.Name)
			@Html.ValidationMessageFor(model => model.Name)
		</div>
        <div class="editor-label">
			@Html.LabelFor(model => model.Description)
		</div>
		<div class="editor-field">
            @Html.TextAreaFor(model => model.Description)
			@*@Html.EditorFor(model => model.Description)*@
			@Html.ValidationMessageFor(model => model.Description)
		</div>
        <div class="editor-label">
			@Html.LabelFor(model => model.UomID)
		</div>
		<div class="editor-field">
            @Html.DropDownListFor(model => model.UomID, BindSelectList.UOMs())			
			@Html.ValidationMessageFor(model => model.UomID)
		</div>
        @*<input type="button" value="Test Method" onclick="UpdateImageList('/UploadedImages/ProductImages/5/DSC_0425_Thumb.jpg', '/UploadedImages/ProductImages/5/Hydrangeas.jpg');" />
        <input type="button" value="Delete Method" onclick="DeleteFromImageList('/UploadedImages/ProductImages/5/DSC_0425_Thumb.jpg');" />*@
        if (Model.ID > 0)
        {
            String jsOnClickHandler = String.Format("ShowImageDialog({0});", Model.ID);
            String noImageVisibility = Model.ProductImages == null || Model.ProductImages.Count == 0 ? "display:block;" : "display:none;";
            <div>                
                <a href="javascript:void(0);" onclick="@jsOnClickHandler">Manage Product Images</a>
                <div id="divManageImageLink" class="image" style="margin-top:5px; @(noImageVisibility)">
                    <a href="javascript:void(0);" onclick="@jsOnClickHandler">@Html.ProductThumb(String.Empty, Model.ID, Model.Name.HtmlEncode())</a>
                </div>
            </div>
        }
        String lightBoxVisibility = Model.ProductImages != null && Model.ProductImages.Count > 0 ? "display:block;" : "display:none;";
        <div id="divProductImages" style="@(lightBoxVisibility)">
            <div class="imageRow">
  	            <div class="set">
                    @if (Model.ProductImages != null && Model.ProductImages.Count > 0)
                    {
                        @Html.GetProductImagesLightboxHtml(Model.ProductImages)
                    }
                </div>
            </div>
        </div>
        <div class="editor-label">
			@Html.LabelFor(model => model.Price)
		</div>
		<div class="editor-field">
			@Html.EditorFor(model => model.Price)
			@Html.ValidationMessageFor(model => model.Price)                
		</div> 
        @Html.HiddenFor(model => model.ID)
        if (_HasValidationError)
        {
            @Html.Hidden("hdnSelectedValues", Model.DynamicProperties.UrlEncode(), new { id = "hdnSelectedValues" })
        }	    
        <div id="divDynamicProperty"></div>
    
	    <input type="submit" value="Save" /> @Html.PrivateLink("Back to List", "List", "Product")
        //Category Selection Dialog Box Start
        <div id="divCategoryDialog">            
            @Html.SelectableCategoryList(_Categories, false, Model.CategoryID)
            <div class="clear"></div>            
        </div>
    }
}
</div>
<div id="dialog"></div>
<div id="divImageDialog" style="width:900px; height:560px;">
    <iframe id="iframeImageList" scrolling="no" frameborder="0" src="" style="width:100%;"></iframe>
</div>

@section PageHeadSection
{
    @Html.JavaScript("jquery.validate.min.js", Url)
    @Html.JavaScript("jquery.validate.unobtrusive.min.js", Url)
    <link rel="stylesheet" href="@Url.Content("~/Content/lightbox.css")" type="text/css" />
    @Html.JavaScript("lightbox.js", Url)
    @* Removed for testing but it turned out that without these lightbox is working.
    @Html.JavaScript("jquery-ui-1.8.18.custom.min.js", Url)
    @Html.JavaScript("jquery.smooth-scroll.min.js", Url)*@
}


